<template>
  <view class="cap-query-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="封顶查询列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 查询方式选择 -->
          <up-tabs :list="queryTypeList" :scrollable="false" @change="handleQueryTypeChange"></up-tabs>
          
          <!-- 搜索条件 -->
          <view class="search-section">
            <!-- 车牌号查询 -->
            <view v-if="currentQueryType === 0" class="search-item">
              <up-search v-model="searchForm.plateNumber" :clearabled="true" :showAction="true" 
                placeholder="请输入车牌号" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <u-button type="primary" size="small" @click="handleSearch">搜索</u-button>
                </template>
              </up-search>
              
              <!-- 年月选择 -->
              <view class="date-range">
                <uni-datetime-picker v-model="searchForm.yearMonth" type="yearmonth" 
                  placeholder="请选择年月" @change="handleDateChange" />
              </view>
            </view>
            
            <!-- 用户账号查询 -->
            <view v-if="currentQueryType === 1" class="search-item">
              <up-search v-model="searchForm.userAccount" :clearabled="true" :showAction="true" 
                placeholder="请输入用户账号" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <u-button type="primary" size="small" @click="handleSearch">搜索</u-button>
                </template>
              </up-search>
            </view>
            
            <!-- 封顶金额范围查询 -->
            <view v-if="currentQueryType === 2" class="search-item">
              <view class="amount-range">
                <up-input v-model="searchForm.minAmount" placeholder="最小金额" type="digit" />
                <text class="range-separator">-</text>
                <up-input v-model="searchForm.maxAmount" placeholder="最大金额" type="digit" />
                <u-button type="primary" size="small" @click="handleSearch">搜索</u-button>
              </view>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="cap-query-list">
        <!-- 车牌号查询结果 -->
        <template v-if="currentQueryType === 0">
          <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
            <view class="card-header">
              <view class="title">
                车牌号：<text class="number">{{ item.plateNumber }}</text>
              </view>
            </view>
            <view class="card-content-box">
              <view class="content">
                <view class="item">
                  <text class="label">停车场：</text>
                  <text class="value">{{ item.parkingLot }}</text>
                </view>
                <view class="item">
                  <text class="label">停车金额：</text>
                  <text class="value amount">¥{{ item.parkingAmount }}</text>
                </view>
                <view class="item">
                  <text class="label">停车次数：</text>
                  <text class="value">{{ item.parkingCount }}次</text>
                </view>
              </view>
            </view>
          </view>
        </template>

        <!-- 用户账号/封顶金额查询结果 -->
        <template v-else>
          <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
            <view class="card-header">
              <view class="title">
                车牌号：<text class="number">{{ item.plateNumber }}</text>
              </view>
            </view>
            <view class="card-content-box">
              <view class="content">
                <view class="item">
                  <text class="label">停车场：</text>
                  <text class="value">{{ item.parkingLot }}</text>
                </view>
                <view class="item">
                  <text class="label">停车金额：</text>
                  <text class="value amount">¥{{ item.parkingAmount }}</text>
                </view>
                <view class="item">
                  <text class="label">停车次数：</text>
                  <text class="value">{{ item.parkingCount }}次</text>
                </view>
              </view>
              <view class="card-footer">
                <view class="operate">
                  <u-button type="primary" text="详情" class="custom-style" 
                    @click="handleViewDetail(item)"></u-button>
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>
    </z-paging>

    <CapDetailModal v-model:show="showCapDetailModal" v-model:detailList="capDetailList" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import CapDetailModal from './components/CapDetailModal.vue'

const { bool: showCapDetailModal, setTrue: openCapDetailModal, setFalse: closeCapDetailModal } = useBoolean();

// 查询方式选项卡数据
const queryTypeList = [
  { name: '车牌号查询' },
  { name: '用户账号查询' },
  { name: '封顶金额查询' },
];
const currentQueryType = ref(0);

// 搜索表单数据
const searchForm = reactive({
  plateNumber: '',
  userAccount: '',
  minAmount: '',
  maxAmount: '',
  yearMonth: '',
});

// 封顶详情数据
const capDetailList = ref([]);
// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 查询方式切换事件
const handleQueryTypeChange = (e) => {
  const newIndex = e.index;
  if (currentQueryType.value === newIndex) {
    return;
  }

  currentQueryType.value = newIndex;
  
  // 清空搜索表单
  searchForm.plateNumber = '';
  searchForm.userAccount = '';
  searchForm.minAmount = '';
  searchForm.maxAmount = '';
  searchForm.yearMonth = '';
  
  // 清空列表
  currentList.value = [];
  
  // 重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  if (currentQueryType.value === 0) {
    searchForm.plateNumber = '';
    searchForm.yearMonth = '';
  } else if (currentQueryType.value === 1) {
    searchForm.userAccount = '';
  } else {
    searchForm.minAmount = '';
    searchForm.maxAmount = '';
  }
  
  if (paging.value) {
    paging.value.reload();
  }
};

// 年月选择事件
const handleDateChange = (e) => {
  searchForm.yearMonth = e;
};

// 详情
const handleViewDetail = async (item) => {
  try {
    // 模拟获取封顶详情数据
    const mockDetailData = [
      {
        orderNo: 'ORD202312010001',
        plateNumber: item.plateNumber,
        payableAmount: '15.00',
        entryTime: '2023-12-01 08:30:00',
        exitTime: '2023-12-01 10:30:00'
      },
      {
        orderNo: 'ORD202312010002',
        plateNumber: item.plateNumber,
        payableAmount: '25.00',
        entryTime: '2023-12-01 14:00:00',
        exitTime: '2023-12-01 16:30:00'
      }
    ];
    
    capDetailList.value = mockDetailData;
    openCapDetailModal();
  } catch (error) {
    console.error('获取封顶详情失败:', error);
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

// 获取封顶列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentQueryType.value)

  const params = {
    pageNum: pageNo,
    pageSize,
    queryType: currentQueryType.value
  }

  // 根据查询方式添加不同的搜索参数
  if (currentQueryType.value === 0) {
    if (searchForm.plateNumber) {
      params.plateNumber = searchForm.plateNumber;
    }
    if (searchForm.yearMonth) {
      params.yearMonth = searchForm.yearMonth;
    }
  } else if (currentQueryType.value === 1 && searchForm.userAccount) {
    params.userAccount = searchForm.userAccount;
  } else if (currentQueryType.value === 2 && (searchForm.minAmount || searchForm.maxAmount)) {
    params.minAmount = searchForm.minAmount;
    params.maxAmount = searchForm.maxAmount;
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 模拟API调用，实际项目中应该调用真实的API
    const mockData = generateMockData(params);
    
    paging.value.complete(mockData.records || [])
  } catch (error) {
    paging.value.complete(false)
  }
}

// 生成模拟数据
const generateMockData = (params) => {
  if (params.queryType === 0) {
    // 车牌号查询 - 返回停车记录列表
    return {
      records: [
        {
          plateNumber: params.plateNumber || '京A12345',
          parkingLot: '万达广场停车场',
          parkingAmount: '15.00',
          parkingCount: 3
        },
        {
          plateNumber: params.plateNumber || '京A12345',
          parkingLot: '银泰中心停车场',
          parkingAmount: '25.00',
          parkingCount: 5
        }
      ]
    };
  } else {
    // 用户账号/封顶金额查询 - 返回车牌号和停车信息列表
    const records = [
      {
        plateNumber: '京A12345',
        parkingLot: '万达广场停车场',
        parkingAmount: '40.00',
        parkingCount: 8
      },
      {
        plateNumber: '京B67890',
        parkingLot: '银泰中心停车场',
        parkingAmount: '60.00',
        parkingCount: 12
      },
      {
        plateNumber: '京C11111',
        parkingLot: '华润万象城停车场',
        parkingAmount: '30.00',
        parkingCount: 6
      }
    ];
    
    // 如果是封顶金额查询，根据金额范围过滤
    if (params.queryType === 2 && (params.minAmount || params.maxAmount)) {
      return {
        records: records.filter(item => {
          const amount = parseFloat(item.parkingAmount);
          const min = params.minAmount ? parseFloat(params.minAmount) : 0;
          const max = params.maxAmount ? parseFloat(params.maxAmount) : Infinity;
          return amount >= min && amount <= max;
        })
      };
    }
    
    return { records };
  }
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
    queryType: 0
  })
});
</script>

<style scoped lang="scss">
.cap-query-list {
  padding: 20px;
}

.search-section {
  margin-top: 20rpx;
  
  .search-item {
    margin-bottom: 20rpx;
    
    .date-range {
      margin-top: 20rpx;
    }
    
    .amount-range {
      display: flex;
      align-items: center;
      gap: 10rpx;
      
      .range-separator {
        font-size: 28rpx;
        color: #666;
        margin: 0 10rpx;
      }
      
      .u-button {
        width: 80rpx;
        flex-shrink: 0;
      }
    }
  }
}

// 列表卡片样式
.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .card-header {
    padding: 24rpx 30rpx 16rpx;
    border-bottom: 1px solid #f5f5f5;
    
    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      
      .number {
        color: #1890ff;
      }
    }
  }
  
  .card-content-box {
    padding: 20rpx 30rpx;
    
    .content {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }
        
        .value {
          font-size: 26rpx;
          color: #333;
          text-align: right;
          
          &.amount {
            color: #ff6b35;
            font-weight: bold;
          }
        }
      }
    }
    
    .card-footer {
      margin-top: 24rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f5f5f5;
      
      .operate {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;
        
        .custom-style {
          border-radius: 8rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}
</style>